package com.oig.sys.oauth.config;

import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import com.oig.common.constants.CommonConstants;
import com.oig.sys.oauth.handler.AuthenticationExceptionEntryPoint;
import com.oig.sys.oauth.provider.enumber.CustomizeENumberAuthenticationConverter;
import com.oig.sys.oauth.provider.enumber.CustomizeENumberAuthenticationProvider;
import com.oig.sys.oauth.provider.password.CustomizeNamePasswordAuthenticationConverter;
import com.oig.sys.oauth.provider.password.CustomizeNamePasswordAuthenticationProvider;
import com.oig.sys.security.config.CacheConstants;
import com.oig.sys.security.support.SecurityUser;
import com.oig.sys.security.support.SecurityUserMixin;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
import org.springframework.security.oauth2.server.authorization.token.DelegatingOAuth2TokenGenerator;
import org.springframework.security.oauth2.server.authorization.token.JwtGenerator;
import org.springframework.security.oauth2.server.authorization.token.OAuth2AccessTokenGenerator;
import org.springframework.security.oauth2.server.authorization.token.OAuth2RefreshTokenGenerator;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenClaimsSet;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.SecurityFilterChain;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.time.Duration;
import java.util.List;
import java.util.UUID;

/**
 * 过滤器链的顺序也非常重要
 * authorizationServerSecurityFilterChain 这个配置先加载
 */
@Configuration
@RequiredArgsConstructor
public class OAuth2AuthorizationServerConfig {

    private final JdbcTemplate jdbcTemplate ;
    private final DaoAuthenticationProvider daoAuthenticationProvider;

    @Bean
    @Order(0)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception{
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
                .tokenEndpoint(token->token.accessTokenRequestConverter(new CustomizeNamePasswordAuthenticationConverter())
                        .accessTokenRequestConverter(new CustomizeENumberAuthenticationConverter()))
                .authorizationEndpoint(authorizationEndpoint -> authorizationEndpoint.consentPage("/sso/confirm_access"))
                .oidc(Customizer.withDefaults())	// Enable OpenID Connect 1.0
        ;
        http
                // Redirect to the login page when not authenticated from the authorization endpoint
                .exceptionHandling((exceptions) -> exceptions
                        .authenticationEntryPoint(new AuthenticationExceptionEntryPoint())
                )
                // Accept access tokens for User Info and/or Client Registration
                .oauth2ResourceServer().opaqueToken();
        //要允许跨域，corsFilter在swagger 里面已经配置了，这边不需要再配置
        DefaultSecurityFilterChain securityFilterChain = http.cors().and().formLogin(Customizer.withDefaults()).build();
        addCustomizeOAuth2GrantAuthenticationProvider(http);
        return securityFilterChain;
    }


    @Bean
    public RegisteredClientRepository registeredClientRepository() {
        //需要另外写个维护 注册客户端
        JdbcRegisteredClientRepository registeredClientRepository =  new JdbcRegisteredClientRepository(jdbcTemplate);
        //sys
        RegisteredClient client = registeredClientRepository.findByClientId("sys");
        if (client==null){
            client = RegisteredClient.withId(UUID.randomUUID().toString())
                    .clientId("sys")
                    .clientSecret(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("sys_secret_r12"))
                    .clientName("优链用户中心")
                    .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
                    .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
                    .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                    .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
                    .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
                    .authorizationGrantType(AuthorizationGrantType.PASSWORD)
                    .authorizationGrantType(new AuthorizationGrantType(CommonConstants.GANT_TYPE_U_CODE))
                    .redirectUri("http://127.0.0.1:9900/callback.html")
                    //.scope(OidcScopes.OPENID)
                    .scope("all")
                    .tokenSettings(TokenSettings.builder()
                            .accessTokenFormat(OAuth2TokenFormat.REFERENCE) //opaqueToken 需要加
                            .accessTokenTimeToLive(Duration.ofHours(9))
                            .refreshTokenTimeToLive(Duration.ofDays(2))
                            .build())
                    .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
                    .build();
            registeredClientRepository.save(client);
        }


        return registeredClientRepository;
    }


    /**
     * jwt 令牌格式 Header.Payload.Signature  Header（头部）; Payload（负载）; Signature（签名）
     */
    @Bean
    public JWKSource<SecurityContext> jwkSource() {
        KeyPair keyPair = generateRsaKey();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAKey rsaKey = new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .keyID(UUID.randomUUID().toString())
                .build();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return new ImmutableJWKSet<>(jwkSet);
    }

    private static KeyPair generateRsaKey() {
        KeyPair keyPair;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        }
        catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }

    @Bean
    public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
        return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
    }

    /**
     * 默认端点
     *  .authorizationEndpoint("/oauth2/authorize")
     * 	.tokenEndpoint("/oauth2/token")
     * 	.jwkSetEndpoint("/oauth2/jwks")
     * 	.tokenRevocationEndpoint("/oauth2/revoke")
     * 	.tokenIntrospectionEndpoint("/oauth2/introspect")
     * 	.oidcClientRegistrationEndpoint("/connect/register")
     * 	.oidcUserInfoEndpoint("/userinfo");
     */
    @Bean
    public AuthorizationServerSettings authorizationServerSettings() {
        return AuthorizationServerSettings.builder().build();
    }


    @Bean
    public OAuth2AuthorizationService oAuth2AuthorizationService(RegisteredClientRepository registeredClientRepository) {
        //令牌发放记录 token存在数据库里了
        JdbcOAuth2AuthorizationService oAuth2AuthorizationService = new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository);
        JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper rowMapper = new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper(registeredClientRepository);
        ObjectMapper objectMapper = new ObjectMapper();
        ClassLoader classLoader = JdbcOAuth2AuthorizationService.class.getClassLoader();
        List<Module> securityModules = SecurityJackson2Modules.getModules(classLoader);
        objectMapper.registerModules(securityModules);
        objectMapper.registerModule(new OAuth2AuthorizationServerJackson2Module());
        objectMapper.addMixIn(SecurityUser.class, SecurityUserMixin.class);
        rowMapper.setObjectMapper(objectMapper);
        oAuth2AuthorizationService.setAuthorizationRowMapper(rowMapper);
        return oAuth2AuthorizationService ;
    }

    @Bean
    public OAuth2AuthorizationConsentService oAuth2AuthorizationConsentService(RegisteredClientRepository registeredClientRepository) {
        //授权确认记录
        return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository);
    }



    @Bean
    public OAuth2TokenGenerator<?> tokenGenerator(){
        JwtGenerator jwtGenerator = new JwtGenerator(new NimbusJwtEncoder(jwkSource()));
//        jwtGenerator.setJwtCustomizer(context -> {
//            if (AuthorizationGrantType.PASSWORD.equals(context.getAuthorizationGrantType())) {
//                JwtClaimsSet.Builder claims = context.getClaims();
//                SecurityUser securityUser = (SecurityUser) context.getPrincipal().getPrincipal();
//                claims.claim("sub", securityUser);
//            }
//        });
        OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
        accessTokenGenerator.setAccessTokenCustomizer(context -> {
            if (AuthorizationGrantType.PASSWORD.equals(context.getAuthorizationGrantType())
                    || context.getAuthorizationGrantType().equals(new AuthorizationGrantType(CommonConstants.GANT_TYPE_U_CODE))) {
                OAuth2TokenClaimsSet.Builder claims = context.getClaims();
                SecurityUser securityUser = (SecurityUser) context.getPrincipal().getPrincipal();
                claims.claim(CacheConstants.ATTR_USER, securityUser);
            }
        });
        OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
        return new DelegatingOAuth2TokenGenerator(jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
    }
    private void addCustomizeOAuth2GrantAuthenticationProvider(HttpSecurity http){
        AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
        OAuth2AuthorizationService authorizationService = http.getSharedObject(OAuth2AuthorizationService.class);
        CustomizeNamePasswordAuthenticationProvider namePasswordAuthenticationProvider
                = new CustomizeNamePasswordAuthenticationProvider(authorizationService, tokenGenerator(), authenticationManager);
        CustomizeENumberAuthenticationProvider customizeENumberAuthenticationProvider
                = new CustomizeENumberAuthenticationProvider(authorizationService, tokenGenerator(), authenticationManager);
        // 处理 UsernamePasswordAuthenticationToken  自定义的CustomizeDaoAuthenticationProvider被注入
        http.authenticationProvider(daoAuthenticationProvider);
        // 处理 CustomizeNamePasswordAuthenticationToken
        http.authenticationProvider(namePasswordAuthenticationProvider);
        // 处理 CustomizeENumberAuthenticationToken
        http.authenticationProvider(customizeENumberAuthenticationProvider);
    }

}
